package cn.danger.com.fragment.user;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.assist.ImageSize;

import java.io.File;
import java.util.Map;

import cn.danger.com.activity.CommonActivity;
import cn.danger.com.activity.R;
import cn.danger.com.fragment.BackHandledFragment;
import cn.danger.com.presenter.UserInfoPresenter;
import cn.danger.com.presenter.UserInfoPresenterImpl;
import cn.danger.com.util.Check;
import cn.danger.com.util.Constants;
import cn.danger.com.util.DensityUtil;
import cn.danger.com.util.FileCacheService;
import cn.danger.com.util.FileUtil;
import cn.danger.com.util.ImageLoaderUtil;
import cn.danger.com.view.CommonView;
import cn.danger.com.widget.MyCircleImageView;
import cn.danger.com.widget.MyPopupWindow;

/**
 * Created by 俊 on 2016/12/28.
 */
public class UserInfoFragment extends BackHandledFragment implements View.OnClickListener, CommonView {

    private boolean hadIntercept;
    private View view;
    private Toolbar toolbar;
    private CommonActivity activity;
    private RelativeLayout user_photo_layout;
    private MyCircleImageView user_photo_imageView;
    private RelativeLayout nick_name_layout;
    private TextView nick_name_textView;
    private RelativeLayout email_layout;
    private TextView email_textView;
    private RelativeLayout phone_layout;
    private TextView phone_textView;
    private RelativeLayout modify_password_layout;
    private AppCompatButton logout_button;
    private TextView bottom_textView;
    private MyPopupWindow popupWindow;
    private static final int PHOTO_REQUEST_GALLERY = 1;
    private static final int PHOTO_REQUEST_CAMERA = 2;
    private static final int PHOTO_REQUEST_CUT = 3;
    private File tempFile;
    private File file;
    private ProgressDialog dialog;
    private UserInfoPresenter presenter;
    private Bitmap bitmap;
    private float alpha = 1.0f;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    backgroundAlpha((float) msg.obj);
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_user_info, container, false);

        bindView();
        bindEvent();

        return view;
    }

    @Override
    public void bindView() {
        activity = (CommonActivity) getActivity();
        toolbar = (Toolbar) view.findViewById(R.id.toolbar);
        user_photo_layout = (RelativeLayout) view.findViewById(R.id.user_photo_layout);
        user_photo_imageView = (MyCircleImageView) view.findViewById(R.id.user_photo_imageView);
        nick_name_layout = (RelativeLayout) view.findViewById(R.id.nick_name_layout);
        nick_name_textView = (TextView) view.findViewById(R.id.nick_name_textView);
        email_layout = (RelativeLayout) view.findViewById(R.id.email_layout);
        email_textView = (TextView) view.findViewById(R.id.email_textView);
        phone_layout = (RelativeLayout) view.findViewById(R.id.phone_layout);
        phone_textView = (TextView) view.findViewById(R.id.phone_textView);
        modify_password_layout = (RelativeLayout) view.findViewById(R.id.modify_password_layout);
        logout_button = (AppCompatButton) view.findViewById(R.id.logout_button);
        bottom_textView = (TextView) view.findViewById(R.id.bottom_textView);

        Map<String, String> map = (Map<String, String>) new FileCacheService(activity).getSharePreference("userInfo");
        if (map.get("photo") != null) {
            new ImageLoaderUtil(new ImageSize(35, 35), user_photo_imageView, map.get("photo"), activity).load();
        } else {
            user_photo_imageView.setImageResource(R.mipmap.default_photo);
        }
        if (map.get("nick_name") != null) {
            nick_name_textView.setText(map.get("nick_name"));
        } else {
            nick_name_textView.setText(map.get("phone"));
        }
        email_textView.setText(map.get("email"));
        phone_textView.setText(map.get("phone"));

        popupWindow = new MyPopupWindow(activity);
        popupWindow.setItem1TextView("拍照");
        popupWindow.setItem2TextView("从相册选择");

        dialog = new ProgressDialog(activity, ProgressDialog.THEME_HOLO_LIGHT);
        dialog.setMessage("正在执行...");
        dialog.setCanceledOnTouchOutside(false);

        presenter = new UserInfoPresenterImpl(activity, this);
    }

    @Override
    public void bindEvent() {
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.finish();
            }
        });
        user_photo_layout.setOnClickListener(this);
        nick_name_layout.setOnClickListener(this);
        email_layout.setOnClickListener(this);
        phone_layout.setOnClickListener(this);
        modify_password_layout.setOnClickListener(this);
        logout_button.setOnClickListener(this);

        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (alpha < 1.0f) {
                            try {
                                Thread.sleep(4);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            Message message = Message.obtain();
                            message.what = 1;
                            alpha += 0.01f;
                            message.obj = alpha;
                            handler.sendMessage(message);
                        }
                    }
                }).start();
            }
        });
        popupWindow.setOnClickItem1Listener(new MyPopupWindow.OnClickItem1Listener() {
            @Override
            public void onClick() {
                camera();
                popupWindow.dismiss();
            }
        });

        popupWindow.setOnClickItem2Listener(new MyPopupWindow.OnClickItem2Listener() {
            @Override
            public void onClick() {
                gallery();
                popupWindow.dismiss();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_photo_layout:
                popupWindow.setAnimationStyle(R.style.popupwindow_anim);
                popupWindow.showAsDropDown(bottom_textView, 0, -DensityUtil.dip2px(activity, 1));
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (alpha > 0.5f) {
                            try {
                                Thread.sleep(4);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            Message message = Message.obtain();
                            message.what = 1;
                            alpha -= 0.01f;
                            message.obj = alpha;
                            handler.sendMessage(message);
                        }
                    }
                }).start();
                break;
            case R.id.nick_name_layout:
                ModifyNickNameFragment nickNameFragment = new ModifyNickNameFragment();
                Bundle nick_name_bundle = new Bundle();
                nick_name_bundle.putString("nick_name", nick_name_textView.getText().toString());
                nickNameFragment.setArguments(nick_name_bundle);
                getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.container, nickNameFragment).commit();
                break;
            case R.id.email_layout:
                ModifyEmailFragment emailFragment = new ModifyEmailFragment();
                Bundle email_bundle = new Bundle();
                email_bundle.putString("email", email_textView.getText().toString());
                emailFragment.setArguments(email_bundle);
                getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.container, emailFragment).commit();
                break;
            case R.id.phone_layout:
                ModifyPhoneFragment phoneFragment = new ModifyPhoneFragment();
                Bundle phone_bundle = new Bundle();
                phone_bundle.putString("phone", phone_textView.getText().toString());
                phoneFragment.setArguments(phone_bundle);
                getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.container, phoneFragment).commit();
                break;
            case R.id.modify_password_layout:
                getFragmentManager().beginTransaction().addToBackStack(null).replace(R.id.container, new ModifyPasswordFragment()).commit();
                break;
            case R.id.logout_button:
                presenter.logout();
                showMessage(Constants.SUCCESS_TO_LOGOUT);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onBackPressed() {
        if (hadIntercept) {
            return false;
        } else {
            hadIntercept = true;
            return true;
        }
    }


    /**
     * 从相册获取
     */
    public void gallery() {
        // 激活系统图库，选择一张图片
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
        startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
    }

    /**
     * 从相机获取
     */
    public void camera() {
        // 激活相机
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        // 判断存储卡是否可以用，可用进行存储
        if (Check.avaiableMedia()) {
            tempFile = new File(Environment.getExternalStorageDirectory(), FileUtil.getFileName());
            // 从文件中创建uri
            Uri uri = Uri.fromFile(tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
        startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PHOTO_REQUEST_GALLERY) {
            // 从相册返回的数据
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
                crop(uri);
            }

        } else if (requestCode == PHOTO_REQUEST_CAMERA) {
            // 从相机返回的数据
            if (Check.avaiableMedia()) {
                crop(Uri.fromFile(tempFile));
            } else {
                Toast.makeText(activity, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
            }

        } else if (requestCode == PHOTO_REQUEST_CUT) {
            // 从剪切图片返回的数据
            if (data != null) {
                bitmap = data.getParcelableExtra("data");
                String fileName = FileUtil.getFileName();
                FileUtil.saveBitmapFile(bitmap, Environment.getExternalStorageDirectory() + "/" + fileName);
                file = new File(Environment.getExternalStorageDirectory() + "/" + fileName);
                presenter.modifyPhoto(file);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /***
     * 剪切图片
     *
     * @param uri
     */
    private void crop(Uri uri) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 50);
        intent.putExtra("outputY", 50);

        intent.putExtra("outputFormat", "JPEG");// 图片格式
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    @Override
    public void showDialog() {
        dialog.show();
    }

    @Override
    public void hideDialog() {
        dialog.dismiss();
    }

    @Override
    public void showMessage(String message) {
        Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
        if (message.equals(Constants.SUCCESS_TO_UPDATE_PHOTO)) {
            user_photo_imageView.setImageBitmap(bitmap);
            Intent intent = new Intent("update_user");
            intent.putExtra("update", "photo");
            activity.sendBroadcast(intent);
            file.delete();
        }
        if (message.equals(Constants.SUCCESS_TO_LOGOUT)) {
            Intent intent = new Intent("update_user");
            intent.putExtra("update", "logout");
            activity.sendBroadcast(intent);
            activity.finish();
        }
    }

    private void backgroundAlpha(float alpha) {
        WindowManager.LayoutParams layoutParams = activity.getWindow().getAttributes();
        layoutParams.alpha = alpha;
        activity.getWindow().setAttributes(layoutParams);
        activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    }

}